/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sg.edu.nus.iss.pacman.manager.socket;

import sg.edu.nus.iss.pacman.dao.Maze;
import sg.edu.nus.iss.pacman.manager.dao.MazeManager;
import sg.edu.nus.iss.pacman.midlet.PacManScreen;
import sg.edu.nus.iss.pacman.net.socket.ServletConnection;
import sg.edu.nus.iss.pacman.net.socket.SocketClientListener;

/**
 * A socket client manager.
 * @author Tabiul Mahmood
 */
public class SocketClientManager implements SocketClientListener
{
    private PacManScreen screen;
    private ServletConnection connection;

    /**
     * Creates a new instance of SocketClientManager.
     * @param serverURL the server URL
     * @param screen the screen
     */
    public SocketClientManager(String serverURL, PacManScreen screen)
    {
        this.screen = screen;
        connection = new ServletConnection(serverURL, this);
    }

    /**
     * Downloads the maze.
     * @param mazeName the maze name
     */
    public void downloadMaze(String mazeName)
    {
        connection.downloadMaze(mazeName);
    }

    public void received(Maze maze)
    {
        if (maze.getMazeName() != null)
        {
            addToPersistence(maze);
            screen.displayInfo("Map " + maze.getMazeName() + " has been successfully downloaded");
        }
        else
        {
            screen.displayInfo("Error downloading the Map");
        }
    }

    private void addToPersistence(Maze maze)
    {
        MazeManager manager = new MazeManager();
        manager.saveMaze(maze);
    }
}
